package org.example.aio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/25 13:46
 */
public class AsyncTimeClientHandler implements CompletionHandler<Void, AsyncTimeClientHandler>, Runnable {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(AsyncTimeClientHandler.class);

    private AsynchronousSocketChannel client;
    private final String host;
    private final int port;
    private CountDownLatch latch;

    public AsyncTimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            this.client = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            log.error("error=", e);
        }
    }

    @Override
    public void run() {
        this.latch = new CountDownLatch(1);
        this.client.connect(new InetSocketAddress(host, port), this, this);
        try {
            this.latch.await();
        } catch (InterruptedException e) {
            log.error("error=", e);
        }
        try {
            this.client.close();
        } catch (IOException e) {
            log.error("error=", e);
        }
    }

    @Override
    public void completed(Void result, AsyncTimeClientHandler attachment) {
        final byte[] req = "QUERY TIME ORDER".getBytes();
        final ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        this.client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer buffer) {
                if (buffer.hasRemaining()) {
                    client.write(buffer, buffer, this);
                } else {
                    final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            attachment.flip();
                            final byte[] bytes = new byte[attachment.remaining()];
                            attachment.get(bytes);
                            final String body = new String(bytes, StandardCharsets.UTF_8);
                            log.info("Now is : {}", body);
                            latch.countDown();
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            try {
                                client.close();
                                latch.countDown();
                            } catch (IOException e) {
                                log.error("error=", e);
                            }
                        }
                    });
                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {

            }
        });
    }

    @Override
    public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
        log.error("error=", exc);
        try {
            this.client.close();
            this.latch.countDown();
        } catch (IOException e) {
            log.error("error=", e);
        }
    }

}